package com.summer.filesync.manager;

import com.summer.filesync.database.dao.FileMetadataDAO;
import com.summer.filesync.database.dao.impl.FileMetadataDAOImpl;
import com.summer.filesync.manager.service.*;
import com.summer.filesync.model.FileMetadata;
import com.summer.filesync.model.manager.*;
import com.summer.filesync.util.Logger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 高级文件管理器 提供企业级文件管理功能，包括批量操作、版本控制、智能分析等 */
public class AdvancedFileManager {
  private static final Logger logger = Logger.getLogger(AdvancedFileManager.class);

  // 核心服务组件
  private final FileOperationService fileOperationService;
  private final FileAnalysisService fileAnalysisService;
  private final FileVersionService fileVersionService;
  private final FileSearchService fileSearchService;
  private final FileStatisticsService fileStatisticsService;
  private final FileRecycleBinService recycleBinService;

  // 数据访问层
  private final FileMetadataDAO fileMetadataDAO;

  // 线程池
  private final ExecutorService executorService;

  // 单例实例
  private static AdvancedFileManager instance;

  private AdvancedFileManager() {
    this.fileMetadataDAO = new FileMetadataDAOImpl();
    this.executorService = Executors.newFixedThreadPool(8);

    // 初始化服务组件
    this.fileOperationService = new FileOperationService(fileMetadataDAO, executorService);
    this.fileAnalysisService = new FileAnalysisService(fileMetadataDAO);
    this.fileVersionService = new FileVersionService(fileMetadataDAO);
    this.fileSearchService = new FileSearchService(fileMetadataDAO);
    this.fileStatisticsService = new FileStatisticsService(fileMetadataDAO);
    this.recycleBinService = new FileRecycleBinService(fileMetadataDAO);

    logger.info("高级文件管理器初始化完成");
  }

  /** 获取单例实例 */
  public static synchronized AdvancedFileManager getInstance() {
    if (instance == null) {
      instance = new AdvancedFileManager();
    }
    return instance;
  }

  // ==================== 批量文件操作 ====================

  /** 批量复制文件 */
  public CompletableFuture<BatchOperationResult> batchCopyFiles(
      List<String> sourcePaths, String destinationDirectory) {
    return fileOperationService.batchCopyFiles(sourcePaths, destinationDirectory);
  }

  /** 批量移动文件 */
  public CompletableFuture<BatchOperationResult> batchMoveFiles(
      List<String> sourcePaths, String destinationDirectory) {
    return fileOperationService.batchMoveFiles(sourcePaths, destinationDirectory);
  }

  /** 批量删除文件 */
  public CompletableFuture<BatchOperationResult> batchDeleteFiles(List<String> filePaths) {
    return fileOperationService.batchDeleteFiles(filePaths);
  }

  /** 批量重命名文件 */
  public CompletableFuture<BatchOperationResult> batchRenameFiles(Map<String, String> renameMap) {
    return fileOperationService.batchRenameFiles(renameMap);
  }

  // ==================== 文件分析功能 ====================

  /** 检测重复文件 */
  public List<DuplicateFileGroup> findDuplicateFiles() {
    return fileAnalysisService.findDuplicateFiles();
  }

  /** 分析存储使用情况 */
  public StorageAnalysisResult analyzeStorageUsage() {
    return fileAnalysisService.analyzeStorageUsage();
  }

  /** 分析文件类型分布 */
  public FileTypeDistribution analyzeFileTypeDistribution() {
    return fileAnalysisService.analyzeFileTypeDistribution();
  }

  /** 查找大文件 */
  public List<FileMetadata> findLargeFiles(long minSizeBytes, int limit) {
    return fileAnalysisService.findLargeFiles(minSizeBytes, limit);
  }

  /** 查找旧文件 */
  public List<FileMetadata> findOldFiles(long olderThanDays, int limit) {
    return fileAnalysisService.findOldFiles(olderThanDays, limit);
  }

  // ==================== 文件版本管理 ====================

  /** 创建文件版本 */
  public FileVersion createFileVersion(String filePath, String comment) {
    return fileVersionService.createVersion(filePath, comment);
  }

  /** 获取文件版本历史 */
  public List<FileVersion> getFileVersionHistory(String filePath) {
    return fileVersionService.getVersionHistory(filePath);
  }

  /** 恢复文件到指定版本 */
  public boolean restoreFileVersion(String filePath, String versionId) {
    return fileVersionService.restoreVersion(filePath, versionId);
  }

  /** 比较文件版本 */
  public FileDifference compareFileVersions(String filePath, String version1, String version2) {
    return fileVersionService.compareVersions(filePath, version1, version2);
  }

  // ==================== 文件搜索功能 ====================

  /** 按文件名搜索 */
  public CompletableFuture<List<FileMetadata>> searchByName(String pattern, boolean caseSensitive) {
    FileSearchCriteria criteria = new FileSearchCriteria();
    criteria.setName(pattern);
    criteria.setCaseSensitive(caseSensitive);
    return fileSearchService.searchFiles(criteria);
  }

  /** 按文件内容搜索 */
  public CompletableFuture<List<FileMetadata>> searchByContent(String keywords) {
    return fileSearchService.searchByContent(keywords, Arrays.asList("."));
  }

  /** 高级搜索 */
  public CompletableFuture<List<FileMetadata>> advancedSearch(FileSearchCriteria criteria) {
    return fileSearchService.searchFiles(criteria);
  }

  /** 重建搜索索引 */
  public CompletableFuture<Boolean> rebuildSearchIndex() {
    return fileSearchService.buildSearchIndex(Arrays.asList(".")).thenApply(v -> true);
  }

  // ==================== 文件统计功能 ====================

  /** 获取文件系统统计 */
  public CompletableFuture<FileSystemStatistics> getFileSystemStatistics() {
    return fileStatisticsService.generateFileSystemStatistics(Arrays.asList("."));
  }

  /** 获取目录统计 */
  public CompletableFuture<DirectoryStatistics> getDirectoryStatistics(String directoryPath) {
    return fileStatisticsService.generateDirectoryStatistics(directoryPath);
  }

  /** 获取文件活动统计 */
  public CompletableFuture<FileActivityStatistics> getFileActivityStatistics(int days) {
    return fileStatisticsService.generateFileActivityStatistics(Arrays.asList("."), days);
  }

  /** 生成存储使用报告 */
  public CompletableFuture<StorageUsageReport> generateStorageReport() {
    return fileStatisticsService.generateStorageUsageReport(Arrays.asList("."));
  }

  // ==================== 回收站功能 ====================

  /** 将文件移至回收站 */
  public CompletableFuture<Boolean> moveToRecycleBin(String filePath) {
    return recycleBinService.moveToRecycleBin(filePath);
  }

  /** 从回收站恢复文件 */
  public CompletableFuture<Boolean> restoreFromRecycleBin(String recycleBinId) {
    return recycleBinService.restoreFromRecycleBin(recycleBinId);
  }

  /** 清空回收站 */
  public CompletableFuture<Integer> emptyRecycleBin() {
    return recycleBinService.emptyRecycleBin();
  }

  /** 获取回收站内容 */
  public List<RecycleBinItem> getRecycleBinContents() {
    return recycleBinService.getRecycleBinItems();
  }

  // ==================== 系统管理功能 ====================

  /** 执行系统维护 */
  public CompletableFuture<MaintenanceResult> performMaintenance() {
    return CompletableFuture.supplyAsync(
        () -> {
          MaintenanceResult result = new MaintenanceResult();

          try {
            logger.info("开始执行系统维护...");

            // 清理临时文件
            int tempFilesDeleted = fileOperationService.cleanupTempFiles();
            result.setTempFilesDeleted(tempFilesDeleted);

            // 清理过期版本
            int versionsDeleted = fileVersionService.cleanupOldVersions();
            result.setVersionsDeleted(versionsDeleted);

            // 优化数据库 (简化实现)
            boolean dbOptimized = true; // fileMetadataDAO.optimizeDatabase();
            result.setDatabaseOptimized(dbOptimized);

            // 重建索引
            boolean indexRebuilt =
                fileSearchService.buildSearchIndex(Arrays.asList(".")).thenApply(v -> true).get();
            result.setIndexRebuilt(indexRebuilt);

            result.setSuccess(true);
            logger.info("系统维护完成");

          } catch (Exception e) {
            logger.error("系统维护失败", e);
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
          }

          return result;
        },
        executorService);
  }

  /** 获取系统健康状态 */
  public SystemHealthStatus getSystemHealth() {
    SystemHealthStatus status = new SystemHealthStatus();

    try {
      // 检查磁盘空间
      StorageAnalysisResult storage = fileAnalysisService.analyzeStorageUsage();
      status.setDiskSpaceUsage(storage.getUsedSpacePercentage());

      // 检查数据库状态 (简化实现)
      status.setDatabaseHealth(true); // fileMetadataDAO.checkDatabaseHealth();

      // 检查重复文件数量
      List<DuplicateFileGroup> duplicates = fileAnalysisService.findDuplicateFiles();
      status.setDuplicateFileCount(duplicates.size());

      // 检查回收站大小
      List<RecycleBinItem> recycleBinItems = recycleBinService.getRecycleBinItems();
      status.setRecycleBinSize(recycleBinItems.size());

      status.setHealthy(true);

    } catch (Exception e) {
      logger.error("获取系统健康状态失败", e);
      status.setHealthy(false);
      status.setErrorMessage(e.getMessage());
    }

    return status;
  }

  /** 关闭管理器 */
  public void shutdown() {
    logger.info("正在关闭高级文件管理器...");

    // 关闭各个服务
    fileSearchService.shutdown();
    fileVersionService.shutdown();

    // 关闭线程池
    if (executorService != null && !executorService.isShutdown()) {
      executorService.shutdown();
    }

    logger.info("高级文件管理器已关闭");
  }
}
